import { get } from 'lodash'
import { getResourceNum } from '@/components/storybook/utilties/tools'

export default (features, integrations, rules) => {
  return features.reduce((result, record) => {
    const product = result.find(i => i.appId === record.appId)
    const rule = rules.find(i => i.appId === record.appId && i.type === 13)
    const code = get(rule, 'threshold.value')
    const resoures = integrations.find(i => i.dimension1 === code && record.type === 2)

    if (product) {
      const integration = product.integrationList.find(i => i.configCode === record.configcode)
      if (record.type_v === 'plan' && record.metadata) {
        product.metadata = record.metadata
      }
      if (record.type === 2 && code === record.configcode && resoures) {
        product.integrationLimit = resoures
        product.integrationList = [{
          configCode: record.configcode,
          configName: record.configname,
          icon: record.icon
        }]
        product.resourceNum = getResourceNum(resoures)
      } else if (record.type !== 2 && !integration) {
        product.integrationList.push({
          configCode: record.configcode,
          configName: record.configname,
          icon: record.icon
        })
      }
    } else {
      const { type_v: v, metadata, ...rest } = record
      const item = {
        ...rest,
        type_v: v,
        integrationList: []
      }
      if (v === 'plan' && metadata) {
        item.metadata = metadata
      }
      if (record.type === 2 && code === record.configcode && resoures) {
        item.integrationLimit = resoures
        item.integrationList = [{
          configCode: record.configcode,
          configName: record.configname,
          icon: record.icon
        }]
        item.resourceNum = getResourceNum(resoures)
      }

      item.subscriptionStatus = record.subscriptionstatus

      result.push(item)
    }

    return result
  }, []).filter(record => record.type !== 2 || record.resourceNum)
}
